package nkr1pt.popkorn.properties;

import com.google.inject.Inject;
import java.io.File;
import java.util.TimerTask;
import nkr1pt.popkorn.events.EventBus;
import nkr1pt.popkorn.events.PopkornEvent.EventType;
import nkr1pt.popkorn.events.PopkornEventFactory;

/**
 * Polls the property file for changes and throws a PropertyFileChangedEvent accordingly.
 *
 * @author Kristof Vanhaeren
 */
public class PropertyFileWatcher extends TimerTask {

    private EventBus eventBus;
    private PopkornEventFactory eventFactory;
    private long timeStamp;
    private File file;

    @Inject
    public PropertyFileWatcher(EventBus eventBus, PopkornEventFactory eventFactory, PropertyLoader propertyLoader) {
        this.eventBus = eventBus;
        this.eventFactory = eventFactory;
        file = propertyLoader.getPropertiesFile();
        this.timeStamp = file.lastModified();
    }

    @Override
    public final void run() {
        long tstamp = file.lastModified();

        if (this.timeStamp != tstamp) {
            this.timeStamp = tstamp;
            onChange(file);
        }
    }

    protected void onChange(File file) {
        eventBus.fireEvent(eventFactory.newEvent(EventType.PROPERTYFILE_CHANGED));
    }
}